//
//  ZDNewAddressController.m
//  ZDPension
//
//  Created by 刘甲奇 on 2017/6/19.
//  Copyright © 2017年 maker. All rights reserved.
//

#import "ZDNewAddressController.h"
#import "ZDInputFieldCell.h"
#import "ZDCityPickerController.h"
#import "MakerTools.h"

static NSString *const ZDInputFieldCellId = @"ZDInputFieldCell";

@interface ZDNewAddressController ()

/**
 <#Description#>
 */
@property(nonatomic, strong) NSArray *titleArray;
/**
 <#Description#>
 */
@property(nonatomic, strong) NSArray *placeArray;
/**
 姓名
 */
@property(nonatomic, copy) NSString *name;
/**
 电话
 */
@property(nonatomic, copy) NSString *phoneNumber;
/**
 地区
 */
@property(nonatomic, copy) NSString *areaInfo;
/**
 地址
 */
@property(nonatomic, copy) NSString *address;


/**
 cityPicker
 */
@property(nonatomic, strong) ZDCityPickerController *cityPickerController;

@end

@implementation ZDNewAddressController

- (void)setupUI
{
    [super setupUI];
    self.title = @"新建收货地址";
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveClick)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZDInputFieldCell" bundle:nil] forCellReuseIdentifier:ZDInputFieldCellId];
    
    ZDCityPickerController *cityPickerController = [[ZDCityPickerController alloc] init];
    cityPickerController.view.frame = CGRectMake(0, LEScreenHeight - 216 -64, LEScreenWidth, 216);
    cityPickerController.view.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    self.cityPickerController = cityPickerController;
    [self addChildViewController:cityPickerController];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectCity:) name:SELECT_CITY_NOTIFICATION object:nil];
}
- (void)loadData
{
    self.titleArray = @[@"收货人:",@"联系电话:",@"收货地址:",@""];
    self.placeArray = @[@"输入姓名",@"输入手机号",@"选择城市",@"具体地址(街道,楼号等)"];
    [self.tableView reloadData];
}
#pragma mark- 网络请求
- (void)requestAddAddress
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.name forKey:@"true_name"];
    [dict setObject:self.address forKey:@"address"];
    [dict setObject:self.areaInfo forKey:@"area_info"];
    [dict setObject:self.phoneNumber forKey:@"tel_phone"];
    [dict setObject:@"250000" forKey:@"area_id"];
    [dict setObject:@"02" forKey:@"city_id"];
    [dict setObject:@"" forKey:@"mob_phone"];

    [SVProgressHUD showWithStatus:@"正在加载中"];
    __weak typeof (self) weakSelf = self;
    [API requestPostAppendKey:AddAddressUrl params:dict success:^(NSDictionary *successCode) {
        [SVProgressHUD dismiss];
        ZDLog(@"%s---%d---%@",__func__,__LINE__,successCode);
        NSDictionary *datas = successCode[@"datas"];
        NSString *error = datas[@"error"];
        if (error)
        {
            [weakSelf addNoDataViewWithTipText:error];
            [weakSelf.dataSource removeAllObjects];
        }else
        {
            [weakSelf hiddenNoDataView];
            [SVProgressHUD showInfoWithStatus:@"添加成功"];
            
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter]postNotificationName:NEW_ADDRESS_NOTIFICATION object:nil];
        }
        [weakSelf.tableView reloadData];
        
    } falure:^(NSError *er) {
        [SVProgressHUD showInfoWithStatus:@"网络错误"];
        [SVProgressHUD dismiss];
    }];
}

#pragma mark- tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZDInputFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:ZDInputFieldCellId forIndexPath:indexPath];
    cell.titleLabel.text = self.titleArray[indexPath.row];
    cell.inputField.placeholder = self.placeArray[indexPath.row];
    if (indexPath.row == 1) {
        cell.inputField.keyboardType = UIKeyboardTypeNumberPad;
    }
    if (indexPath.row == 2) {
        cell.inputField.enabled = NO;
    }
    if (indexPath.row == 3) {
        cell.inputFieldLeft.constant = 10;
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2) {
        ZDLog(@"%s---%d---选择省份去",__func__,__LINE__);
        [self closeKeyBoard];
        [self.view addSubview:self.cityPickerController.view];
    }
}
#pragma mark- 点击事件
- (void)saveClick
{
    ZDLog(@"%s---%d---保存",__func__,__LINE__);
    self.name = [self getFieldText:0];
    if (self.name.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请输入姓名"];
        return;
    }
    self.phoneNumber = [self getFieldText:1];
    if (![MakerTools isPhoneNumber:self.phoneNumber]) {
        [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号"];
        return;
    }
    self.areaInfo = [self getFieldText:2];
    if (self.areaInfo.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请选择地区"];
        return;
    }
    self.address = [self getFieldText:3];
    if (self.address.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请输入详细地址"];
        return;
    }
    
    [self requestAddAddress];
}
- (void)selectCity:(NSNotification *)notification
{
    NSString *cityString = notification.object;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
    ZDInputFieldCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    dispatch_async(dispatch_get_main_queue(), ^{
        cell.inputField.text = cityString;
    });
}
#pragma mark- privateMethod
- (void)closeKeyBoard
{
    for (int i = 0; i < 4; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        ZDInputFieldCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        [cell.inputField resignFirstResponder];
    }
}
/**
 根据行号获取输入框的内容
 
 @param indexPathRow <#indexPathRow description#>
 @return <#return value description#>
 */
- (NSString *)getFieldText:(NSInteger)indexPathRow
{
    NSIndexPath *path = [NSIndexPath indexPathForRow:indexPathRow inSection:0];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:path];
    if ([cell isKindOfClass:[ZDInputFieldCell class]])
    {
        ZDInputFieldCell *cells = (ZDInputFieldCell *)cell;
        return  cells.inputField.text;
    }
    return @"";
}
@end
